package com.ruoyi.info.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.vo.AuditingEnterpriseBase;
import com.ruoyi.info.vo.ProductAdaptationVo;
import com.ruoyi.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.info.domain.Product;
import com.ruoyi.info.service.IProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品信息Controller
 * 
 * @author wangshi
 * @date 2023-06-07
 */
@RestController
@RequestMapping("/info/product")
public class ProductController extends BaseController
{
    @Autowired
    private IProductService productService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询产品信息列表
     */
    @PreAuthorize("@ss.hasPermi('info:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(Product product)
    {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 导出产品信息列表
     */
    @PreAuthorize("@ss.hasPermi('info:product:export')")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Product product) throws IOException {
        productService.exportProduct(response,product);
//        List<Product> list = productService.selectProductList(product);
//        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
//        util.exportExcel(response, list, "产品信息数据");
    }

    /**
     * 导出企业基地 批量导入模板
     */
    @PreAuthorize("@ss.hasPermi('info:product:templateDownload')")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/template/download")
    public void templateDownload(HttpServletResponse response) throws IOException {
        productService.templateDownload(response);
    }

    /**
     * 导入企业基地信息 模板导入
     */
    @PreAuthorize("@ss.hasPermi('info:product:templateRender')")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/template/render")
    public AjaxResult templateRender(MultipartFile file) throws IOException, ParseException {
        return toAjax(productService.templateRender(file));
    }

    /**
     * 获取产品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('info:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(productService.selectProductById(id));
    }

    /**
     * 新增产品信息
     */
    @PreAuthorize("@ss.hasPermi('info:product:add')")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductAdaptationVo productAdaptationVo)
    {
        productAdaptationVo.setCreateBy(getUsername());
        return toAjax(productService.insertProduct(productAdaptationVo));
    }

    /**
     * 修改产品信息
     */
    @PreAuthorize("@ss.hasPermi('info:product:edit')")
    @Log(title = "产品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductAdaptationVo productAdaptationVo)
    {
        productAdaptationVo.setUpdateBy(getUsername());
        return toAjax(productService.updateProduct(productAdaptationVo));
    }

    /**
     * 删除产品信息
     */
    @PreAuthorize("@ss.hasPermi('info:product:remove')")
    @Log(title = "产品信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(productService.deleteProductByIds(ids));
    }

    /**
     * 产品审核
     * @param auditingEnterpriseBase 产品审核字段
     * @return
     */
    @PreAuthorize("@ss.hasPermi('info:product:auditing')")
    @Log(title = "产品审核", businessType = BusinessType.UPDATE)
    @PostMapping("/auditing")
    public AjaxResult auditing(@RequestBody AuditingEnterpriseBase auditingEnterpriseBase){
        auditingEnterpriseBase.setCreateBy(getUsername());
        return toAjax(productService.auditingProduct(auditingEnterpriseBase));
    }

    @GetMapping("/template")
    public void getTemplate(){
        List<SysDictData> datas = dictTypeService.selectDictDataByType("product_industry");
        if (StringUtils.isNull(datas)){
            datas = new ArrayList<>();
        }
        String[] labels = new String[datas.size()];
        for (int i = 0; i < datas.size(); i++) {
            labels[i] = datas.get(i).getDictLabel();
        }
        String path  ="D:\\student_code\\jia-project\\信息技术服务平台\\ruoyi-admin\\doc\\output.xlsx";
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        XSSFSheet sheet = (XSSFSheet) workbook.createSheet("产品信息");
        // 创建行
        Row row = sheet.createRow(0);
        // 设置标题
        String[] ths = new String[]{
                "产品名称",
                "产品类型",
                "行业",
                "版本型号",
                "产品介绍",
                "厂商",
                "联系人",
                "联系方式",
                "关键词",
                "数据来源",
        };
        for (int i = 0; i < ths.length; i++) {
            // 创建单元格并设置值
            Cell cell = row.createCell(i);
            cell.setCellValue(ths[i]);
        }
        // 创建行
        Row row1 = sheet.createRow(1);
        for (int i = 0; i < ths.length; i++) {
            // 创建单元格并设置值
            Cell cell = row1.createCell(i);
            if(i == 1){
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(labels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
        }


        String[] pdThs = new String[]{
                "产品信息序号",
                "适配OS",
                "适配时间",
                "适配OS类型",
                "适配状态",
                "适配OS版本",
                "兼容等级",
                "OS小版本",
                "认证状态",
                "适配平台",
                "收费/免费",
                "适配CPU型号",
                "上架情况",
                "备注",
                "适配验证情况"
        };
        String[] dictTypes = new String[]{
                "",
                "audition_os",
                "",
                "auditiing_os_type",
                "auditing_status",
                "",
                "compatibility_level",
                "",
                "certification_status",
                "adaptation_platform",
                "auditing_cost",
                "adapted_cpu_model",
                "auditing_listing",
                "",
                "adaptation_verification_status",

        };

        // 创建工作表
        XSSFSheet sheet1 = (XSSFSheet) workbook.createSheet("适配信息");
        // 创建行
        Row row11 = sheet1.createRow(0);
        for (int i = 0; i < pdThs.length; i++) {
            // 创建单元格并设置值
            Cell cell = row11.createCell(i);
            cell.setCellValue(pdThs[i]);
        }
        Row row12 = sheet1.createRow(1);
        for (int i = 0; i < pdThs.length; i++) {

            // 创建单元格并设置值
            Cell cell = row12.createCell(i);
            if(dictTypes[i].length() > 0){
                List<SysDictData> datas1 = dictTypeService.selectDictDataByType(dictTypes[i]);
                if (StringUtils.isNull(datas1)){
                    datas1 = new ArrayList<>();
                }
                String[] labels1 = new String[datas1.size()];
                for (int j = 0; j < datas1.size(); j++) {
                    labels1[j] = datas1.get(j).getDictLabel();
                }
                System.out.println(Arrays.toString(labels1));
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet1);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(labels1);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet1.addValidationData(validation);
            }else{
                cell.setCellValue(dictTypes[i]);
                if(i == 2){
                    // 设置日期格式
                    String dateFormat = "yyyy-MM-dd HH:mm:ss";
                    DataFormat dataFormat = workbook.createDataFormat();
                    CellStyle dateStyle = workbook.createCellStyle();
                    dateStyle.setDataFormat(dataFormat.getFormat(dateFormat));
                    cell.setCellStyle(dateStyle);
                }

            }
        }
        // 写入文件
        try (FileOutputStream outputStream = new FileOutputStream(path)) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/render/template")
    public void renderTemplate() throws IOException {
        String path  ="D:\\student_code\\jia-project\\信息技术服务平台\\ruoyi-admin\\doc\\output.xlsx";
        // 创建workbook对象
        Workbook workbook = WorkbookFactory.create(new FileInputStream(path));
        // 获取sheet对象
        Sheet sheet = workbook.getSheetAt(0);
        System.out.println(sheet.getLastRowNum());
        // 使用循环遍历每一行和每一个单元格
        for (int i = 0; i < sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            System.out.println(row.getLastCellNum());
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                String value = cell.getStringCellValue();
                System.out.println(value);
            }
        }
        // 关闭workbook对象和输入流
        workbook.close();
    }
}
